package com.yyryyty.chapter3;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @Description :
 * @Author : YTY
 * @Date : 2021-01-16 09:57
 */
public class ExecuteAround {

    public static void main(String[] args) throws IOException {

//        System.out.println(processFileLimited());

//        String twoLines = processFile((BufferedReader b) -> b.readLine() + b.readLine());
//        System.out.println(twoLines);
//        System.out.println(processFile((BufferedReader b) -> b.readLine() + b.readLine()));
//        System.out.println(processFile(b -> b.readLine() + b.readLine()));

//        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
//        System.out.println(filter(list, integer -> integer % 2 == 0));

//        forEach(
//                Arrays.asList(1, 2, 3, 4, 5),
//                integer -> System.out.println(integer)
//        );

//        List<Integer> list = map(
//                Arrays.asList("lambdas", "in", "action"),
//                s -> s.length()
//        );
//        System.out.println(list);

    }

    public static String processFileLimited() throws IOException {
        try (BufferedReader br =
                     new BufferedReader(new FileReader("src/main/resources/java8higher/chap3/data.txt"))) {
            return br.readLine();
        }
    }

    public static String processFile(BufferedReaderProcessor p) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader("src/main/resources/java8higher/chap3/data.txt"))) {
            return p.process(br);
        }

    }

    public static <T, R> List<R> map(List<T> list, Function<T, R> f) {

        List<R> result = new ArrayList<>();
        for (T s : list) {
            result.add(f.apply(s));
        }
        return result;
    }

    public static <T> void forEach(List<T> list, Consumer<T> c) {

        for (T i : list) {
            c.accept(i);
        }
    }

    public static <T> List<T> filter(List<T> list, Predicate<T> p) {

        List<T> results = new ArrayList<>();
        for (T s : list) {
            if (p.test(s)) {
                results.add(s);
            }
        }
        return results;
    }

    @FunctionalInterface
    public interface BufferedReaderProcessor {

        String process(BufferedReader b) throws IOException;
    }
}
